package com.eduhzy.ttw.teacher.mvp.presenter;

import android.app.Application;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.decoration.GridSpacingItemDecoration;
import com.eduhzy.ttw.teacher.mvp.model.entity.ChildAreaData;
import com.eduhzy.ttw.teacher.mvp.model.entity.ChooseSchoolData;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.entity.MineClassData;
import com.eduhzy.ttw.commonsdk.entity.SchoolTypeData;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.utils.Utils;
import com.eduhzy.ttw.teacher.R;
import com.eduhzy.ttw.teacher.mvp.contract.ChooseSchoolContract;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


/**
 * @author xubo
 * @date 2018-7-19 10:06:17
 */
@ActivityScope
public class ChooseSchoolPresenter extends BasePresenter<ChooseSchoolContract.Model, ChooseSchoolContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    @Inject
    BaseQuickAdapter<ChooseSchoolData, AutoBaseViewHolder> mAdapter;
    private String schoolTypeCode;

    @Inject
    public ChooseSchoolPresenter(ChooseSchoolContract.Model model, ChooseSchoolContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void getGroupbyAreaMap(String areaCode) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("areaCode", areaCode);
        map.put("groupFlag", 2);
        map.put("pageSize", 1000);
        map.put("pageNo", 1);
        mModel.getGroupbyAreaMap(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    mRootView.showLoading();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    mRootView.hideLoading();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<ChooseSchoolData[]>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<ChooseSchoolData[]> commonData) {
                        if (commonData.isResult()) {
                            mAdapter.getData().clear();
                            List<ChooseSchoolData> list = new ArrayList<>();
                            list.addAll(Arrays.asList(commonData.getData()));
                            mRootView.update(list);
                        }
                    }
                });
    }

    public void getClassByUser() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("userId", SPUtils.getInstance().getString(Constants.USERID));
        mModel.getClassByUser(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();//显示下拉刷新的进度条
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mRootView.hideLoading();//隐藏下拉刷新的进度条
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<CommonData<List<MineClassData>>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<List<MineClassData>> data) {
                        List<MineClassData> list = new ArrayList<>();
                        if (data.isResult()) {
                            list.addAll(data.getData());
                        }
                        mRootView.getClassData(list);
                    }
                });
    }

    public void savePersonGroup(String id) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("userId", SPUtils.getInstance().getString(Constants.USERID));
        map.put("groupId", id);
        mModel.savePersonGroup(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    mRootView.showLoading();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    mRootView.hideLoading();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<Map>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<Map> commonData) {
                        if (commonData.isResult()) {
                            Message msg = Message.obtain();
                            msg.what = EventBusTags.CHOOSE_SCHOOL_SUCCESS;
                            EventBus.getDefault().post(msg, RouterHub.APP_MINESCHOOLACTIVITY);
                            EventBus.getDefault().post(msg, RouterHub.APP_MINEFRAGMENT);
                            mRootView.showMessage("修改成功");
                            mRootView.killMyself();
                        }
                    }
                });


    }

    public void showTransferDialog(List<MineClassData> bzrList) {
        QMUIDialog transfer = getQmuiDialog(R.layout.dialog_transfer);
        TextView title = (TextView) transfer.findViewById(R.id.tv_title);
        title.setText("你即将加入新学校，必须先将自己管理的班级转让:");
        RecyclerView rvList = transfer.findViewById(R.id.rv_list);
        rvList.setVisibility(View.VISIBLE);
        BaseQuickAdapter adapter = new BaseQuickAdapter<MineClassData, AutoBaseViewHolder>(R.layout.rv_item_dialog_transfer, bzrList) {
            @Override
            protected void convert(AutoBaseViewHolder helper, MineClassData item) {
                helper.setText(R.id.tv_name, "· " + item.getBjmc());
            }
        };
        transfer.findViewById(R.id.btn_cancel).setOnClickListener((view) -> {
            transfer.dismiss();
        });
        Button btnOk = transfer.findViewById(R.id.btn_ok);
        btnOk.setOnClickListener((view) -> {
            transfer.dismiss();
            Utils.navigationWithTitle(RouterHub.APP_MINECLASSACTIVITY, Constants.MINECLASS);
        });
        rvList.setLayoutManager(new LinearLayoutManager(mRootView.getActivity()));
        rvList.setAdapter(adapter);
    }


    public void showDropClassDialog(List<MineClassData> normalList, ChooseSchoolData data) {
        QMUIDialog transfer = getQmuiDialog(R.layout.dialog_drop_class);
        TextView schoolName = (TextView) transfer.findViewById(R.id.tv_school_name);
        schoolName.setText(data.getAddressAreaName() + data.getName());
        RecyclerView rvList = transfer.findViewById(R.id.rv_list);
        BaseQuickAdapter adapter = new BaseQuickAdapter<MineClassData, AutoBaseViewHolder>(R.layout.rv_item_dialog_transfer, normalList) {
            @Override
            protected void convert(AutoBaseViewHolder helper, MineClassData item) {
                helper.setText(R.id.tv_name, "· " + item.getBjmc());
            }
        };
        transfer.findViewById(R.id.btn_cancel).setOnClickListener((view) -> {
            transfer.dismiss();
        });
        Button btnOk = transfer.findViewById(R.id.btn_ok);
        btnOk.setOnClickListener((view) -> {
            transfer.dismiss();
            savePersonGroup(data.getId());
        });
        rvList.setLayoutManager(new LinearLayoutManager(mRootView.getActivity()));
        rvList.setAdapter(adapter);
    }

    public void showJoinSchoolDialog(ChooseSchoolData data) {
        QMUIDialog transfer = getQmuiDialog(R.layout.dialog_transfer);
        TextView title = (TextView) transfer.findViewById(R.id.tv_title);
        title.setText("确定加入该学校吗\n\n\n");
        transfer.findViewById(R.id.btn_cancel).setOnClickListener((view) -> {
            transfer.dismiss();
        });
        Button btnOk = transfer.findViewById(R.id.btn_ok);
        btnOk.setText("确定");
        btnOk.setOnClickListener((view) -> {
            transfer.dismiss();
            savePersonGroup(data.getId());
        });
    }

    @NonNull
    private QMUIDialog getQmuiDialog(int resId) {
        QMUIDialog transfer = new QMUIDialog(mRootView.getActivity(), R.style.TransparentDialogTheme);
        transfer.setContentView(resId);
        transfer.show();
        transfer.setCancelable(false);
        Window window = transfer.getWindow();
        //设置窗口位置
        window.setGravity(Gravity.CENTER);
        //获取窗口属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //获取窗口管理者
        WindowManager windowManager = mRootView.getActivity().getWindowManager();
        //获取真机参数
        Display display = windowManager.getDefaultDisplay();
        //设置窗口大小
        //根据autolayout来适配当前大小
        lp.width = (int) (display.getWidth() * 977 / 1080f);
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        //给窗口设置属性
        window.setAttributes(lp);
        return transfer;
    }


    public void getBaseCodeByType() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("type", "BXLX");
        mModel.getBaseCodeByType(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    mRootView.showLoading();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    mRootView.hideLoading();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<List<SchoolTypeData>>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<List<SchoolTypeData>> commonData) {
                        if (commonData.isResult()) {
                            mRootView.getSchoolType(commonData.getData());

                        }
                    }
                });
    }

    public void showAddSchool(List<SchoolTypeData> data, ChildAreaData area, String addressAreaName) {
        schoolTypeCode = "";
        QMUIDialog addSchool = getQmuiDialog(R.layout.dialog_add_school);
        TextView tvArea = addSchool.findViewById(R.id.tv_area);
        EditText etSchool = addSchool.findViewById(R.id.et_school_name);
        tvArea.setText(addressAreaName);
        RecyclerView rvList = addSchool.findViewById(R.id.rv_list);
        rvList.setVisibility(View.VISIBLE);
        BaseQuickAdapter mAdapter = new BaseQuickAdapter<SchoolTypeData, AutoBaseViewHolder>(R.layout.rv_item_dialog_add_school, data) {
            @Override
            protected void convert(AutoBaseViewHolder helper, SchoolTypeData item) {
                QMUIRoundButton button = helper.getView(R.id.tv_name);
                button.setText(item.getName());
                button.setSelected(item.isSelect());
                helper.addOnClickListener(R.id.tv_name);
            }
        };
        addSchool.findViewById(R.id.btn_cancel).setOnClickListener((view) -> {
            addSchool.dismiss();
        });
        Button btnOk = addSchool.findViewById(R.id.btn_ok);
        btnOk.setText("确定");
        btnOk.setOnClickListener((view) -> {
            String schoolName = etSchool.getText().toString();
            if (ObjectUtils.isEmpty(schoolName)) {
                RxUtil.showTipDialog(mRootView.getActivity(), QMUITipDialog.Builder.ICON_TYPE_FAIL, "请输入学校名字", 1500);
                return;
            }
            if (ObjectUtils.isEmpty(schoolTypeCode)) {
                RxUtil.showTipDialog(mRootView.getActivity(), QMUITipDialog.Builder.ICON_TYPE_FAIL, "请选择学段", 1500);
                return;
            }
            addSchool.dismiss();
            saveGroupApply(schoolName, area.getAreaCode(), schoolTypeCode, SPUtils.getInstance().getString(Constants.USERID));
        });
        GridSpacingItemDecoration decoration = new GridSpacingItemDecoration(3, 20, false);
        GridLayoutManager layoutManager = new GridLayoutManager(mRootView.getActivity(), 3);
        rvList.addItemDecoration(decoration);
        rvList.setLayoutManager(layoutManager);
        rvList.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            for (int i = 0; i < data.size(); i++) {
                if (i == position) {
                    schoolTypeCode = data.get(i).getCode();
                    data.get(position).setSelect(true);
                } else {
                    data.get(i).setSelect(false);
                }
            }
            adapter.notifyDataSetChanged();
        });
    }

    public void saveGroupApply(String schoolName, String areaCode, String schoolTypeCode, String userId) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("name", schoolName);
        map.put("areaCode", areaCode);
        map.put("schoolTypeCode", schoolTypeCode);
        map.put("userId", userId);
        mModel.saveGroupApply(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    mRootView.showLoading();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    mRootView.hideLoading();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<Map>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<Map> commonData) {
                        if (commonData.isResult()) {
                            mRootView.showMessage(commonData.getMessage());
                            Message msg = Message.obtain();
                            msg.what = EventBusTags.CHOOSE_SCHOOL_SUCCESS;
                            EventBus.getDefault().post(msg, RouterHub.APP_MINESCHOOLACTIVITY);
                            EventBus.getDefault().post(msg, RouterHub.APP_MINEFRAGMENT);
                            mRootView.killMyself();
                        }
                    }
                });
    }

}
